package com.i2863.receipt.service.impl;

import com.i2863.receipt.dao.AccountRepository;
import com.i2863.receipt.entity.Account;
import com.i2863.receipt.entity.Activity;
import com.i2863.receipt.service.AccountService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Predicate;
import javax.persistence.criteria.Root;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2018/6/8.
 */
@Service
public class AccountServiceImpl implements AccountService{

    @Resource
    private AccountRepository accountRepository;

    @Override
    public Account findByUsername(String username) {
        return accountRepository.findByUsername(username);
    }


    @Override
    public void add(Account account) {
        accountRepository.save(account);
    }

    @Override
    public void del(Integer id) {
        accountRepository.delete(id);
    }

    @Override
    public Page<Account> queryByPage(int pageSize, Integer pageNum, final String queryContent, final Integer siteId) {
        Pageable pageable = new PageRequest(pageNum-1,pageSize, Sort.Direction.DESC,"modifyDate");//jpa从0开始
        Specification<Account> specification = new Specification<Account>() {
            List<Predicate> predicates = new ArrayList<Predicate>();
            @Override
            public Predicate toPredicate(Root<Account> root, CriteriaQuery<?> criteriaQuery, CriteriaBuilder cb) {
                if(StringUtils.isNotBlank(queryContent)){ //添加断言
                    Predicate likeName = cb.like(root.get("username").as(String.class),"%"+queryContent+"%");
                    predicates.add(likeName);
                }
                predicates.add(cb.equal(root.get("site").get("id").as(Integer.class),siteId));
                return cb.and(predicates.toArray(new Predicate[predicates.size()]));
            }
        };
        return accountRepository.findAll(specification,pageable);
    }

    @Override
    public Account findOne(Integer id) {
        return accountRepository.findOne(id);
    }

    @Override
    public void update(Account account) {
        accountRepository.saveAndFlush(account);
    }
}
